package com.mishow.widget;

import java.util.ArrayList;

import com.mishow.R;
import com.mishow.adapter.MenuPopAdatper;
import com.mishow.bean.MenuItemBean;
import com.mishow.utils.DeviceUtil;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
/**
 * 
 * 作者：wei.miao <br/>
 * 描述：搜索弹出窗口
 */
public class MenuPopWindow {
	
	/** Context对象 **/
	private Context mContext;
	/** pop 弹出框 **/
	private PopupWindow menuPw;
	/** 显示数据列表 **/
	private MyListView  menuList;
	/** 显示数据内容 **/
	private ArrayList<MenuItemBean> menuContents;
	/** 数据点击事件 **/
	private OnItemClickListener itemClickListener;

	public MenuPopWindow(Context mContext, ArrayList<MenuItemBean> menuContents) {
		this.mContext = mContext;
		this.menuContents = menuContents;
		initView();
	}

	/**
	 * 初始化
	 */
	private void initView() {
		menuList = (MyListView ) LayoutInflater.from(mContext).inflate(R.layout.discount_listview, null);
		menuPw = new PopupWindow(menuList, DeviceUtil.dip2px(mContext, 83), LayoutParams.WRAP_CONTENT);
		// 必须设置。改变弹出窗口的背景，如果设置成null，点击空白处pop不消失。
		//menuPw.setBackgroundDrawable(new ColorDrawable(-00000));
		menuPw.setBackgroundDrawable(new ColorDrawable(mContext.getResources().getColor(R.color.search_pop_bg)));
		menuPw.setOutsideTouchable(true);
		menuPw.setFocusable(true);

		menuPw.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
			}
		});

		// 如果PopUpWindow内的布局会夺取焦点（如示例ListView）,注意代码
		menuList.setFocusable(false);
		menuList.setFocusableInTouchMode(true);
		// 焦点到了listView上，所以需要监听此处的键盘事件。否则会出现不响应键盘事件的情况
		menuList.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					closePopWin();
				}
				return true;
			}
		});
		initListView();
	}

	/**
	 * 设置列表显示内容
	 */
	private void initListView() {
		MenuPopAdatper adatper = new MenuPopAdatper(mContext, menuContents);
		menuList.setAdapter(adatper);
	}

	/**
	 * 关闭popwindow
	 */
	public void closePopWin() {
		try {
			if (menuPw != null && menuPw.isShowing()) {
				menuPw.dismiss();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 显示弹出框
	 * 
	 * @param view
	 */
	public void showPopWin(View view) {
		try {
			// 显示pop
			menuPw.showAsDropDown(view);
			menuPw.update();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 设置点击事件监听
	 * @param itemClickListener
	 */
	public void setItemClickListener(OnItemClickListener itemClickListener) {
		this.itemClickListener = itemClickListener;
		menuList.setOnItemClickListener(itemClickListener);
	}
	
}
